<template>
  <el-upload
    ref="upload"
    drag
    action="#"
    :limit="1"
    class="drag"
    :before-upload="uploadBefore"
    :auto-upload="true"
    :show-file-list="false"
    :on-exceed="handleExceed"
    :disabled="!form.resourceType || uploadLoading"
  >
    <el-icon v-show="!form.fileName" class="mx-3">
      <upload-filled />
    </el-icon>
    <el-icon v-show="form.fileName" class="mx-3" style="font-size: 16px;" @click.stop="previewMd">
      <search />
    </el-icon>
    <span v-show="!form.fileName">请点击上传或拖拽文件至此处，仅限markdown文件</span>
    <span
      v-show="form.fileName"
      class="neu-ellipse"
      style="display:inline-block;"
    >{{ form.fileName }}</span>
    <el-icon class="el-icon-error ml-2 mr-3 neu-color-blue" @click.stop="editMd">
      <edit />
    </el-icon>
    <el-icon v-show="form.fileName" class="el-icon-error mx-0 mr-3" @click.stop="delfile">
      <delete />
    </el-icon>
    <!-- <i v-show="form.fileName" class="el-icon-error" @click.stop="delfile" /> -->
  </el-upload>

  <el-drawer
    v-model="showDrawer"
    :title="drawerTitle"
    direction="btt"
    size="100%"
    :close-on-press-escape="false"
    :before-close="closeDrawer"
  >
    <MdEditor
      v-if="showDrawer && isEdit"
      v-model="text"
      editor-class="md-detail-view isEdit"
      :toolbars="toolbars"
      @onUploadImg="onUploadImg"
      @onSave="saveMdFile"
      placeholder="请输入markdown内容"
      :toolbars-exclude="toolbarsExc"
    />
    <MdEditor
      v-if="showDrawer && !isEdit"
      :model-value="text"
      editor-class="md-detail-view"
      :toolbars="toolbars"
      :toolbars-exclude="toolbarsExc"
    />
  </el-drawer>
</template>
<script>
import MdEditor from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
export default {
  emits: ['setFile'],
  props: {
    fileId: {
      type: String,
      default: ''
    },
    concatIdList: {
      type: String,
      default: ''
    },
    fileName: {
      type: String,
      default: ''
    },
  },
  components: {
    MdEditor
  },
  mounted () {
    this.form.fileName = this.fileName
  },
  watch: {
    fileName (val) {
      this.form.fileName = val
    }
  },
  data () {
    return {
      showDrawer: false,
      drawerTitle: '实验手册',
      form: {
        resourceType: 'MD',
        fileName: ''
      },
      concatIds: [],
      chooseFile: null,
      uploadLoading: false,
      defaultText: '',
      text: '',
      toolbars: [],
      toolbarsExc: []
    }
  },
  computed: {
    acceptsList () {
      let _list = []
      _list = (this.form.resourceType ? this.fileObject.accepts[this.form.resourceType] : [])
      return _list
    },
    allAcceptsList () {
      let _list = []
      Object.keys(this.fileObject.accepts).map(t => {
        _list = _list.concat(this.fileObject.accepts[t].accept || [])
      })
      return {
        accept: _list || ['*'],
        hint: '仅支持 ' + _list.join('，') + ' 格式'
      }
    }
  },
  methods: {
    closeDrawer (done) {
      if (this.defaultText !== this.text) {
        this.mmsgBox({
          title: '提示信息',
          text: `markdown文件内容有变更，请确认是否保存?`,
          showClose: false,
          actions: [
            {
              key: 'true',
              text: '确定'
            },
            {
              key: 'false',
              text: '取消'
            }
          ]
        }).then(result => {
          if (result) {
            this.saveMdFile()
          }
          done()
        })
      } else {
        done()
      }
    },
    handleExceed () {
      this.$message.warning('只能选择单个文件')
      this.chooseFile = null
      this.form.fileName = null
    },
    uploadBefore (file) {
      let FileExt = file.name.replace(/.+\./, '.')
      if (this.acceptsList.accept && (this.acceptsList.accept[0] !== '*') && (this.acceptsList.accept.indexOf(FileExt.toLowerCase()) === -1)) {
        this.$message({
          type: 'warning',
          message: this.acceptsList.hint + '！'
        })
      } else {
        if (file.name.length > 200) {
          this.$message({
            type: 'warning',
            message: '资源名称不能超过200个字符'
          })
        } else {
          if (FileExt.toLowerCase() === '.md') {
            if (file.size / 1024 / 1024 >= 1) {
              this.$message({
                type: 'warning',
                message: 'Markdown资源大小不能超过1M！'
              })
              return false
            }
          }
          // 上传是否为单个文件
          this.chooseFile = file
          this.$emit('setFile', this.chooseFile, this.concatIds)
          this.form.fileName = file.name
        }
      }
      return false
    },
    delfile () {
      if (this.loading) {
        return
      }
      this.chooseFile = null
      this.form.file = null
      this.form.fileName = null
      this.concatIds = []
      this.$emit('setFile', this.chooseFile, this.concatIds)
    },
    previewMd () {
      this.isEdit = false
      if (this.fileId || this.chooseFile) {
        this.toolbars = []
        this.showDrawer = true
        if (this.chooseFile) {
          let that = this
          this.fileObject.getFileContentText(this.chooseFile, (str) => {
            that.defaultText = str + ''
            that.text = str + ''
          })
        } else if (this.fileId) {
          let that = this
          this.fileObject.getFileContent(this.fileId).then(res => {
            that.defaultText = res.data + ''
            that.text = res.data + ''
          })
        }
      }
    },
    editMd () {
      this.isEdit = true
      this.toolbars = [
        'bold',                         // '加粗',
        'underline',                    //'下划线',
        'italic',                       //'斜体',
        'strikeThrough',                //'删除线',
        'sub',                          //'下标',
        'sup',                          //'上标',
        '-',
        'quote',                        //'引用',
        'unorderedList',                //'无序列表',
        'orderedList',                  //'有序列表',
        'codeRow',                      //'行内代码',
        'code',                         //'块级代码',
        'link',                         //'链接',
        'image',                        //'图片',
        'table',                        //'表格',
        'katex',                        //'公式', 
        '-',
        'revoke',                       //'后退一步',
        'next',                         //'前进一步',
        'save',                         //'保存',
        '=',
        'pageFullscreen',               //'页面内全屏',
        'fullscreen',                   //'屏幕全屏',
        'preview',                      //'内容预览',
        'htmlPreview',                  //'html代码预览',
        'catalog',                      //'目录'
      ]
      if (this.fileId || this.chooseFile) {
        this.showDrawer = true
        if (this.chooseFile) {
          let that = this
          this.fileObject.getFileContentText(this.chooseFile, (str) => {
            that.defaultText = str + ''
            that.text = str + ''
          })
        } else if (this.fileId) {
          let that = this
          this.fileObject.getFileContent(this.fileId).then(res => {
            that.defaultText = res.data + ''
            that.text = res.data + ''
          })
        }
      } else {
        this.showDrawer = true
        this.defaultText = ''
        this.text = ''
      }
    },
    async onUploadImg (files, callback) {
      let that = this
      const resList = await Promise.all(
        Array.from(files).map((file) => {
          return new Promise((rev, rej) => {
            that.fileObject.uploadFileNoTag(file)
              .then((res) => rev(res.data))
              .catch((error) => rej(error));
          });
        })
      );
      callback(resList.map((item) => {
        let arr = item.data || [null]
        let fileObj = arr[0]
        that.concatIds.push(fileObj.eid)
        return that.fileObject.getFileUrl(fileObj.eid)
      }));
    },
    saveMdFile () {
      let file = this.fileObject.saveTextToMdFile(this.text)
      file.name = '实验手册.md'
      this.chooseFile = file
      this.defaultText = this.text
      this.$emit('setFile', this.chooseFile, this.concatIds)
      this.form.fileName = file.name
      this.$message.success('新的实验手册文件已生成，请保存任务')
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~/styles/base.scss";
.drag {
  width: 100%;
  border-radius: 2px;
  text-align: left;
  cursor: pointer;
  display: inline-block;
  background: rgba(0, 0, 0, 0.05);
  .el-icon {
    margin: 0 15px;
    color: $neu-primary-color;
    font-size: 20px;
  }
  span {
    width: calc(100% - 50px);
  }
  .el-icon-error {
    font-size: 16px;
    color: red;
  }
  :deep(.el-upload) {
    display: unset !important;
    .el-upload-dragger {
      width: 100%;
      height: 40px;
      text-align: left;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
}
.isEdit {
  height: 100%;
}
.md-detail-view:not(.isEdit) {
  height: 100%;
  :deep(.md-toolbar-wrapper) {
    display: none;
  }
  :deep(.md-content) {
    height: 100%;
  }
  // :deep(.md-preview-wrapper) {
  //   border-left: 1px solid #e6e6e6;
  // }
}
:deep(.md-input-wrapper) {
  border-right: 1px solid #e6e6e6;
}
</style>